package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @date: 2025/8/16 14:31
 * @author: yz
 * @version: 1.0
 */
@Component
@Slf4j
public class SearchReceiver {


    @Autowired
    private SearchService searchService;
    /**
     * 专辑下架监听
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_ALBUM_LOWER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = {MqConst.ROUTING_ALBUM_LOWER}
    ))
    public void lowerAlbum(Long albumId, Message message, Channel channel){


        try {
            //判断
            if(albumId!=null){

                searchService.lowerAlbum(albumId);
            }
            log.info("专辑下架成功，专辑ID：{}",albumId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }


    }
    /**
     * 专辑上架监听
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value =@Queue(value = MqConst.QUEUE_ALBUM_UPPER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = {MqConst.ROUTING_ALBUM_UPPER}
    ))
    public void upperAlbum(Long albumId, Message message, Channel channel){


        try {
            //判断
            if(albumId!=null){

                searchService.upperAlbum(albumId);
            }
            log.info("专辑上架成功，专辑ID：{}",albumId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }


    }








}
